/**
 * $Id$
 *
 * Copyright (c) 2014 ChinaSoft International, Ltd. All rights reserved
 * JointForce Project
 *
 */
package com.csi.jf.crucible.api.stash;

import java.io.IOException;
import java.nio.charset.Charset;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.chinasofti.ro.bizframework.core.libs.Base64;
import com.csi.jf.crucible.api.crucible.RestClient;
import com.icss.j2ee.util.http.HttpClientException;

/**
 * @Title: ApiTestProject.java
 * @Description: <br>
 *               <br>
 * @Company: Chinasofti
 * @Created on 2014-7-4 下午3:25:41
 * @author zhangmh
 * @version $Revision: 1.0 $
 * @since 1.0
 */
public class ApiTestRepo {
    
    public static final String STASH_HOST = "http://115.29.76.124:7990";
    private String projectKey = "JF-PTS-PRJ";
    private String authorization = "Basic "+Base64.encode("jfpts@chinasofti.com:123456".getBytes());
    private RestClient client = new RestClient(STASH_HOST,authorization);
    
    public static void main(String[] args) throws Exception{
        ApiTestRepo test = new ApiTestRepo();
//          test.testRepoCreateApi();
        //test.testRepoListApi();
        //test.testNewRepoApi();
          test.testCreateProject();
    }
    
    public void testRepoCreateApi() throws HttpClientException, IOException{
        String url = STASH_HOST + "/rest/api/1.0/projects/"+projectKey+"/repos";
        String json = "{"+
            "\"scmId\": \"git\","+//"+projectKey+"
            "\"name\": \"jfpts-repo1\","+
            "\"forkable\": \"false\""+
        "}";
        client.doPost(url,json,false);
        //{"slug":"jfpts-repo1","id":306,"name":"jfpts-repo1","scmId":"git","state":"AVAILABLE","statusMessage":"Available","forkable":false,"project":{"key":"JF-PTS-PRJ","id":346,"name":"JF_PTS_Service_Project","description":"JointForce PTS 专用Git工程","public":false,"type":"NORMAL","isPersonal":false,"link":{"SONAR_URL":"/projects/JF-PTS-PRJ","rel":"self"},"links":{"self":[{"href":"https://git.jointforce.com/projects/JF-PTS-PRJ"}]}},"public":false,"link":{"SONAR_URL":"/projects/JF-PTS-PRJ/repos/jfpts-repo1/browse","rel":"self"},"cloneUrl":"https://zhangmh%40chinasofti.com@git.jointforce.com/scm/jf-pts-prj/jfpts-repo1.git","links":{"clone":[{"href":"ssh://git@git.jointforce.com:7999/jf-pts-prj/jfpts-repo1.git","name":"ssh"},{"href":"https://zhangmh%40chinasofti.com@git.jointforce.com/scm/jf-pts-prj/jfpts-repo1.git","name":"http"}],"self":[{"href":"https://git.jointforce.com/projects/JF-PTS-PRJ/repos/jfpts-repo1/browse"}]}}
    }
    
    public void testRepoListApi() throws HttpClientException, IOException{
        String url = "/rest/api/1.0/projects/"+projectKey+"/repos";
        client.doGet(url,false);
    }
    
    //Create a new repository forked from an existing repository.
    public void testNewRepoApi() throws HttpClientException, IOException{
    	 String url = "/rest/api/1.0/projects/cru267/Portal_rp";
         String json = "{"+
             "\"slug\": \"Portal_rp \","+//"+projectKey+"
             "\"name\": \"null\","+
             "\"forkable\":{ \"cru267\"}"+
         "}";
//         client.doPost(url,json,false);
         doPost(url,json,false);
    }
    
    public void testCreateProject() throws HttpClientException, IOException {
   	 String url = STASH_HOST + "//rest/api/1.0/projects";
   	 StringBuffer sbJson = new StringBuffer();
   	 sbJson
   	.append("{")
   	.append("    \"key\": \"cru267\",")
   	.append("    \"name\": \"Portal_cru\",")
   	.append("    \"description\": \"The description for my cool project.\",")
   	.append("    \"avatar\": \"data:image/png;base64,<base64-encoded-image-data>\"")
   	.append("}")
   	;
//     String json = "{"+
//         "\"slug\": \"Portal_rp \","+//"+projectKey+"
//         "\"name\": \"null\","+
//         "\"forkable\":{ \"cru267\"}"+
//     "}";
//     client.doPost(url,sbJson.toString(),false);
     doPost(url,sbJson.toString(),false);
    }
    
    public String doPost(String url,String json,boolean useToken) throws HttpClientException, IOException{
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
//            url = this.checkUrl(url,useToken);
            HttpPost httpPost = new HttpPost(url);
//            httpPost.setHeader("Content-Type","application/json");
            httpPost.setHeader("Content-Type","application/json;charset=UTF-8");
//            httpPost.setHeader("Accept", "*/*");
            httpPost.setHeader("Accept-Language", "zh-cn");
            httpPost.setHeader("Cache-Control", "no-cache");
//            httpPost.setHeader("Accept-Charset", "UTF-8;");
            httpPost.setHeader("Accept","application/json");
            if(this.authorization!=null){
                httpPost.setHeader("Authorization",this.authorization);
            }
            System.out.println("****************************************************\n");
            System.out.println("do post request for:\n"+url);
            
//            List <NameValuePair> nvps = new ArrayList <NameValuePair>();
//            nvps.add(new BasicNameValuePair("username", "vip"));
//            nvps.add(new BasicNameValuePair("password", "secret"));
//            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
            
            System.out.println("do post data:\n"+json);
//            HttpEntity entity = new StringEntity(json, Charset.forName("utf-8"));
            HttpEntity entity = new StringEntity(json);
            httpPost.setEntity(entity);
            
            CloseableHttpResponse response1 = httpclient.execute(httpPost);
            response1.addHeader("content-type", "application/json");
//            response1.setHeader("content-type","application/json;charset=UTF-8");
            response1.addHeader("Accept", "application/json");
//          response1.setHeader("Accept-Charset", "UTF-8;");
            
            try {
                System.out.println(response1.getStatusLine());
                HttpEntity entity1 = response1.getEntity();
                String retStr = null;
                if(entity1!=null){
                    retStr = EntityUtils.toString(entity1) ;
                    System.out.println("Response:"+retStr);
                    System.out.println("Length:"+entity1.getContentLength());
                    System.out.println("ContentType:"+entity1.getContentType());
                    System.out.println("Encoding:"+entity1.getContentEncoding());
                    return retStr;
                }
            } finally {
                response1.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            httpclient.close();
        }
        return null;
    }
}
